<template>
  <div class="performance-optimization">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>性能优化</h1>
      <p>系统性能分析和优化建议</p>
    </div>

    <!-- 性能概览 -->
    <div class="performance-overview">
      <div class="overview-card">
        <div class="card-icon score-icon">
          <i class="el-icon-trophy"></i>
        </div>
        <div class="card-content">
          <h3>{{ performanceScore }}</h3>
          <p>综合评分</p>
          <div class="score-bar">
            <div class="score-progress" :style="{ width: performanceScore + '%' }"></div>
          </div>
        </div>
      </div>

      <div class="overview-card">
        <div class="card-icon optimization-icon">
          <i class="el-icon-setting"></i>
        </div>
        <div class="card-content">
          <h3>{{ optimizationCount }}</h3>
          <p>优化项目</p>
          <div class="optimization-status">
            <span class="status-item completed">{{ completedCount }} 已完成</span>
            <span class="status-item pending">{{ pendingCount }} 待处理</span>
          </div>
        </div>
      </div>

      <div class="overview-card">
        <div class="card-icon improvement-icon">
          <i class="el-icon-data-line"></i>
        </div>
        <div class="card-content">
          <h3>{{ improvementPercent }}%</h3>
          <p>性能提升</p>
          <div class="improvement-trend">
            <i class="el-icon-top trend-up"></i>
            <span>较上周提升</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 性能分析 -->
    <div class="performance-analysis">
      <el-card class="analysis-card">
        <template #header>
          <div class="card-header">
            <span>性能分析</span>
            <el-button type="primary" @click="runAnalysis">
              <i class="el-icon-search"></i>
              重新分析
            </el-button>
          </div>
        </template>
        <div class="analysis-content">
          <div class="analysis-item" v-for="metric in performanceMetrics" :key="metric.name">
            <div class="metric-info">
              <div class="metric-name">{{ metric.name }}</div>
              <div class="metric-description">{{ metric.description }}</div>
            </div>
            <div class="metric-value">
              <div class="value">{{ metric.value }}</div>
              <div class="status" :class="metric.status">{{ metric.statusText }}</div>
            </div>
            <div class="metric-chart">
              <el-progress :percentage="metric.percentage" :color="getProgressColor(metric.status)" />
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 优化建议 -->
    <div class="optimization-suggestions">
      <el-card class="suggestions-card">
        <template #header>
          <div class="card-header">
            <span>优化建议</span>
            <el-button type="text" @click="refreshSuggestions">
              <i class="el-icon-refresh"></i>
              刷新
            </el-button>
          </div>
        </template>
        <div class="suggestions-list">
          <div class="suggestion-item" v-for="suggestion in suggestions" :key="suggestion.id">
            <div class="suggestion-priority" :class="suggestion.priority">
              {{ suggestion.priority === 'high' ? '高' : suggestion.priority === 'medium' ? '中' : '低' }}
            </div>
            <div class="suggestion-content">
              <div class="suggestion-title">{{ suggestion.title }}</div>
              <div class="suggestion-description">{{ suggestion.description }}</div>
              <div class="suggestion-impact">
                <span class="impact-item">
                  <i class="el-icon-time"></i>
                  预计耗时: {{ suggestion.estimatedTime }}
                </span>
                <span class="impact-item">
                  <i class="el-icon-data-line"></i>
                  预期提升: {{ suggestion.expectedImprovement }}
                </span>
              </div>
            </div>
            <div class="suggestion-actions">
              <el-button type="primary" size="small" @click="implementSuggestion(suggestion)">
                执行优化
              </el-button>
              <el-button type="text" size="small" @click="viewSuggestionDetails(suggestion)">
                查看详情
              </el-button>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 优化任务 -->
    <div class="optimization-tasks">
      <el-card class="tasks-card">
        <template #header>
          <div class="card-header">
            <span>优化任务</span>
            <el-button type="primary" @click="showTaskDialog">
              <i class="el-icon-plus"></i>
              创建任务
            </el-button>
          </div>
        </template>
        <el-table :data="optimizationTasks" style="width: 100%">
          <el-table-column prop="name" label="任务名称" />
          <el-table-column prop="type" label="类型" width="100">
            <template #default="scope">
              <el-tag size="small" :type="getTaskTypeColor(scope.row.type)">
                {{ scope.row.type }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="priority" label="优先级" width="100">
            <template #default="scope">
              <el-tag size="small" :type="getPriorityColor(scope.row.priority)">
                {{ scope.row.priority === 'high' ? '高' : scope.row.priority === 'medium' ? '中' : '低' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag size="small" :type="getStatusColor(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="progress" label="进度" width="150">
            <template #default="scope">
              <el-progress :percentage="scope.row.progress" :color="getProgressColor('good')" />
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button type="text" size="small" @click="viewTaskDetails(scope.row)">
                查看
              </el-button>
              <el-button type="text" size="small" @click="editTask(scope.row)">
                编辑
              </el-button>
              <el-button type="text" size="small" @click="deleteTask(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 任务详情对话框 -->
    <el-dialog
      v-model="taskDialogVisible"
      :title="isEditTaskMode ? '编辑任务' : '创建任务'"
      width="600px"
    >
      <el-form
        :model="taskForm"
        :rules="taskFormRules"
        ref="taskFormRef"
        label-width="100px"
      >
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="taskForm.name" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="任务类型" prop="type">
          <el-select v-model="taskForm.type" placeholder="请选择任务类型">
            <el-option label="数据库优化" value="database" />
            <el-option label="缓存优化" value="cache" />
            <el-option label="代码优化" value="code" />
            <el-option label="系统配置" value="system" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="taskForm.priority" placeholder="请选择优先级">
            <el-option label="高" value="high" />
            <el-option label="中" value="medium" />
            <el-option label="低" value="low" />
          </el-select>
        </el-form-item>
        <el-form-item label="任务描述" prop="description">
          <el-input
            v-model="taskForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入任务描述"
          />
        </el-form-item>
        <el-form-item label="预计耗时" prop="estimatedTime">
          <el-input v-model="taskForm.estimatedTime" placeholder="如：2小时" />
        </el-form-item>
        <el-form-item label="预期提升" prop="expectedImprovement">
          <el-input v-model="taskForm.expectedImprovement" placeholder="如：20%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="taskDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveTask">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'PerformanceOptimization',
  setup() {
    const taskDialogVisible = ref(false)
    const isEditTaskMode = ref(false)
    const taskFormRef = ref(null)

    // 性能数据
    const performanceScore = ref(85)
    const optimizationCount = ref(12)
    const completedCount = ref(8)
    const pendingCount = ref(4)
    const improvementPercent = ref(15)

    // 性能指标
    const performanceMetrics = ref([
      {
        name: 'CPU利用率',
        description: '系统CPU使用效率',
        value: '良好',
        status: 'good',
        statusText: '良好',
        percentage: 85
      },
      {
        name: '内存使用',
        description: '内存使用优化程度',
        value: '优秀',
        status: 'excellent',
        statusText: '优秀',
        percentage: 92
      },
      {
        name: '磁盘IO',
        description: '磁盘读写性能',
        value: '一般',
        status: 'normal',
        statusText: '一般',
        percentage: 68
      },
      {
        name: '网络延迟',
        description: '网络响应时间',
        value: '良好',
        status: 'good',
        statusText: '良好',
        percentage: 78
      },
      {
        name: '数据库查询',
        description: '数据库查询效率',
        value: '需优化',
        status: 'poor',
        statusText: '需优化',
        percentage: 45
      }
    ])

    // 优化建议
    const suggestions = ref([
      {
        id: 1,
        title: '数据库索引优化',
        description: '为常用查询字段添加索引，提高查询效率',
        priority: 'high',
        estimatedTime: '2小时',
        expectedImprovement: '30%'
      },
      {
        id: 2,
        title: '缓存策略优化',
        description: '优化Redis缓存配置，提高缓存命中率',
        priority: 'medium',
        estimatedTime: '1小时',
        expectedImprovement: '15%'
      },
      {
        id: 3,
        title: '代码性能优化',
        description: '优化算法复杂度，减少不必要的计算',
        priority: 'medium',
        estimatedTime: '4小时',
        expectedImprovement: '20%'
      },
      {
        id: 4,
        title: '静态资源优化',
        description: '启用Gzip压缩和CDN加速',
        priority: 'low',
        estimatedTime: '30分钟',
        expectedImprovement: '10%'
      }
    ])

    // 优化任务
    const optimizationTasks = ref([
      {
        id: 1,
        name: '数据库连接池优化',
        type: 'database',
        priority: 'high',
        status: 'completed',
        progress: 100,
        createTime: '2025-01-10 10:00:00'
      },
      {
        id: 2,
        name: 'Redis缓存优化',
        type: 'cache',
        priority: 'medium',
        status: 'running',
        progress: 65,
        createTime: '2025-01-12 14:30:00'
      },
      {
        id: 3,
        name: '前端代码压缩',
        type: 'code',
        priority: 'low',
        status: 'pending',
        progress: 0,
        createTime: '2025-01-14 09:15:00'
      }
    ])

    // 任务表单
    const taskForm = reactive({
      id: null,
      name: '',
      type: '',
      priority: '',
      description: '',
      estimatedTime: '',
      expectedImprovement: ''
    })

    // 表单验证规则
    const taskFormRules = {
      name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
      type: [{ required: true, message: '请选择任务类型', trigger: 'change' }],
      priority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
      description: [{ required: true, message: '请输入任务描述', trigger: 'blur' }]
    }

    // 获取进度条颜色
    const getProgressColor = (status) => {
      switch (status) {
        case 'excellent': return '#67c23a'
        case 'good': return '#409eff'
        case 'normal': return '#e6a23c'
        case 'poor': return '#f56c6c'
        default: return '#409eff'
      }
    }

    // 获取任务类型颜色
    const getTaskTypeColor = (type) => {
      switch (type) {
        case 'database': return 'primary'
        case 'cache': return 'success'
        case 'code': return 'warning'
        case 'system': return 'info'
        default: return 'primary'
      }
    }

    // 获取优先级颜色
    const getPriorityColor = (priority) => {
      switch (priority) {
        case 'high': return 'danger'
        case 'medium': return 'warning'
        case 'low': return 'info'
        default: return 'info'
      }
    }

    // 获取状态颜色
    const getStatusColor = (status) => {
      switch (status) {
        case 'completed': return 'success'
        case 'running': return 'primary'
        case 'pending': return 'info'
        case 'failed': return 'danger'
        default: return 'info'
      }
    }

    // 获取状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 'completed': return '已完成'
        case 'running': return '进行中'
        case 'pending': return '待处理'
        case 'failed': return '失败'
        default: return '未知'
      }
    }

    // 运行分析
    const runAnalysis = () => {
      ElMessage.success('性能分析已启动')
      // 模拟分析过程
      setTimeout(() => {
        ElMessage.success('性能分析完成')
      }, 2000)
    }

    // 刷新建议
    const refreshSuggestions = () => {
      ElMessage.success('优化建议已刷新')
    }

    // 执行优化建议
    const implementSuggestion = (suggestion) => {
      ElMessageBox.confirm(`确定要执行优化建议 "${suggestion.title}" 吗？`)
        .then(() => {
          // 创建优化任务
          const newTask = {
            id: Date.now(),
            name: suggestion.title,
            type: 'optimization',
            priority: suggestion.priority,
            status: 'running',
            progress: 0,
            createTime: new Date().toLocaleString()
          }
          optimizationTasks.value.push(newTask)
          ElMessage.success('优化任务已创建')
        })
        .catch(() => {})
    }

    // 查看建议详情
    const viewSuggestionDetails = (suggestion) => {
      ElMessageBox.alert(suggestion.description, suggestion.title)
    }

    // 显示任务对话框
    const showTaskDialog = () => {
      isEditTaskMode.value = false
      resetTaskForm()
      taskDialogVisible.value = true
    }

    // 编辑任务
    const editTask = (task) => {
      isEditTaskMode.value = true
      Object.assign(taskForm, task)
      taskDialogVisible.value = true
    }

    // 删除任务
    const deleteTask = (task) => {
      ElMessageBox.confirm(`确定要删除任务 "${task.name}" 吗？`)
        .then(() => {
          const index = optimizationTasks.value.findIndex(t => t.id === task.id)
          if (index !== -1) {
            optimizationTasks.value.splice(index, 1)
            ElMessage.success('任务删除成功')
          }
        })
        .catch(() => {})
    }

    // 查看任务详情
    const viewTaskDetails = (task) => {
      ElMessageBox.alert(`任务状态：${getStatusText(task.status)}\n进度：${task.progress}%`, task.name)
    }

    // 重置任务表单
    const resetTaskForm = () => {
      Object.assign(taskForm, {
        id: null,
        name: '',
        type: '',
        priority: '',
        description: '',
        estimatedTime: '',
        expectedImprovement: ''
      })
      if (taskFormRef.value) {
        taskFormRef.value.resetFields()
      }
    }

    // 保存任务
    const saveTask = () => {
      taskFormRef.value.validate((valid) => {
        if (valid) {
          if (isEditTaskMode.value) {
            // 编辑任务
            const index = optimizationTasks.value.findIndex(t => t.id === taskForm.id)
            if (index !== -1) {
              optimizationTasks.value[index] = { ...taskForm }
              ElMessage.success('任务更新成功')
            }
          } else {
            // 创建任务
            const newTask = {
              ...taskForm,
              id: Date.now(),
              status: 'pending',
              progress: 0,
              createTime: new Date().toLocaleString()
            }
            optimizationTasks.value.push(newTask)
            ElMessage.success('任务创建成功')
          }
          taskDialogVisible.value = false
          resetTaskForm()
        }
      })
    }

    return {
      taskDialogVisible,
      isEditTaskMode,
      taskFormRef,
      performanceScore,
      optimizationCount,
      completedCount,
      pendingCount,
      improvementPercent,
      performanceMetrics,
      suggestions,
      optimizationTasks,
      taskForm,
      taskFormRules,
      getProgressColor,
      getTaskTypeColor,
      getPriorityColor,
      getStatusColor,
      getStatusText,
      runAnalysis,
      refreshSuggestions,
      implementSuggestion,
      viewSuggestionDetails,
      showTaskDialog,
      editTask,
      deleteTask,
      viewTaskDetails,
      resetTaskForm,
      saveTask
    }
  }
}
</script>

<style scoped>
.performance-optimization {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 28px;
  color: #333;
  margin-bottom: 10px;
}

.page-header p {
  font-size: 16px;
  color: #666;
}

.performance-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.overview-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: #fff;
}

.score-icon {
  background: linear-gradient(45deg, #ffd700, #ffed4a);
}

.optimization-icon {
  background: linear-gradient(45deg, #409eff, #66d9ef);
}

.improvement-icon {
  background: linear-gradient(45deg, #67c23a, #95de64);
}

.card-content {
  flex: 1;
}

.card-content h3 {
  font-size: 28px;
  color: #333;
  margin-bottom: 5px;
}

.card-content p {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.score-bar {
  width: 100%;
  height: 4px;
  background: #f0f0f0;
  border-radius: 2px;
  overflow: hidden;
}

.score-progress {
  height: 100%;
  background: linear-gradient(90deg, #67c23a, #95de64);
  transition: width 0.3s ease;
}

.optimization-status {
  display: flex;
  gap: 15px;
  font-size: 12px;
}

.status-item.completed {
  color: #67c23a;
}

.status-item.pending {
  color: #e6a23c;
}

.improvement-trend {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 12px;
  color: #67c23a;
}

.trend-up {
  color: #67c23a;
}

.performance-analysis {
  margin-bottom: 30px;
}

.analysis-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.analysis-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.analysis-item {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr;
  gap: 20px;
  align-items: center;
  padding: 15px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.analysis-item:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.metric-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.metric-name {
  font-weight: 500;
  color: #333;
}

.metric-description {
  font-size: 12px;
  color: #666;
}

.metric-value {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.value {
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.status {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
}

.status.excellent {
  background: #f0f9ff;
  color: #67c23a;
}

.status.good {
  background: #f0f9ff;
  color: #409eff;
}

.status.normal {
  background: #fef0e6;
  color: #e6a23c;
}

.status.poor {
  background: #fef0f0;
  color: #f56c6c;
}

.optimization-suggestions {
  margin-bottom: 30px;
}

.suggestions-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.suggestions-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.suggestion-item {
  display: flex;
  align-items: flex-start;
  gap: 15px;
  padding: 20px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.suggestion-item:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.suggestion-priority {
  width: 40px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  color: #fff;
  flex-shrink: 0;
}

.suggestion-priority.high {
  background: #f56c6c;
}

.suggestion-priority.medium {
  background: #e6a23c;
}

.suggestion-priority.low {
  background: #909399;
}

.suggestion-content {
  flex: 1;
}

.suggestion-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.suggestion-description {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.suggestion-impact {
  display: flex;
  gap: 20px;
  font-size: 12px;
  color: #999;
}

.impact-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.suggestion-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
  flex-shrink: 0;
}

.optimization-tasks {
  margin-bottom: 20px;
}

.tasks-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .performance-overview {
    grid-template-columns: 1fr;
  }
  
  .analysis-item {
    grid-template-columns: 1fr;
    gap: 10px;
  }
  
  .suggestion-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .suggestion-actions {
    flex-direction: row;
    width: 100%;
    justify-content: flex-end;
  }
}
</style> 